import serial
from PyQt5 import QtCore, QtGui, QtWidgets
from serial.serialutil import SerialException
import app_serial
from output_python_file import Ui_Dialog
import sys
import threading

serial_port = app_serial.SerialPort()

ui = Ui_Dialog()


def poll_serial_port():
    """
    从指定的串口对象读取数据。

    :param serial_port: 一个打开的串口对象，例如通过serial.Serial创建。
    :param read_size: 一次读取的字节数。
    """

    data_waiting = serial_port.in_waiting()
    if data_waiting > 0:
        data = serial_port.read(data_waiting)
        if data:
            print("从串口读取到的数据:", data)
            ui.textBrowser.append(str(data, 'utf-8'))
            # 滚动到文本末尾
            ui.textBrowser.ensureCursorVisible()


def start_polling(poll_interval=0.2):
    """
    启动定时轮询串口数据。
    :param poll_interval: 轮询间隔（秒）。
    """

    # 定义轮询函数
    def polling():
        poll_serial_port()
        # 设置定时器再次轮询
        threading.Timer(poll_interval, polling).start()

    # 启动轮询
    polling()


def pushButton_start_clicked(self):
    print("打开串口！")
    box_text = ui.comboBox_baudrate.currentText()
    if box_text == "其他":
        serial_port.port = ui.comboBox_com.currentText()
        serial_port.baudrate = ui.lineEdit.text()
    else:
        serial_port.port = ui.comboBox_com.currentText()
        serial_port.baudrate = ui.comboBox_baudrate.currentText()

    print(f"com:{serial_port.port}, baudrate:{serial_port.baudrate}")
    serial_port.open()
    start_polling()


def pushButton_stop_clicked(self):
    print("关闭串口！")
    serial_port.close()


def comboBox_baudrate_changed(self):
    sel = ui.comboBox_baudrate.currentText()
    if sel == "其他":
        print("选择了其他")
        ui.comboBox_baudrate.hide()
        ui.lineEdit.show()
    else:
        print(f"选择了{sel}")
        ui.comboBox_baudrate.show()
        ui.lineEdit.hide()


def app_ui_init():
    app = QtWidgets.QApplication(sys.argv)
    Dialog = QtWidgets.QDialog()
    # ui = Ui_Dialog()
    ui.setupUi(Dialog)
    ui.pushButton_start.clicked.connect(pushButton_start_clicked)
    ui.pushButton_stop.clicked.connect(pushButton_stop_clicked)

    # 获取COM端口列表
    com_ports = serial_port.get_com_ports()
    # 打印COM端口列表
    print("Available COM ports:")
    for com_port in com_ports:
        print(com_port)

    for com_port in com_ports:
        ui.comboBox_com.addItem(com_port)

    ui.comboBox_baudrate.addItem('115200')
    ui.comboBox_baudrate.addItem('9600')
    ui.comboBox_baudrate.addItem('其他')
    ui.comboBox_baudrate.currentIndexChanged.connect(comboBox_baudrate_changed)
    ui.lineEdit.hide()
    Dialog.show()
    sys.exit(app.exec_())
